<template>
	<view>
		<!-- :historyForm="detailObj" -->
		<disHistory 
			:titleName="detailObj.orderType=== 'history_not_repaired' ? '病害变更' : '修改病害'" 
			compoType="change" 
			:beforeChange="beforeForm"
			@updateSubmit="updateSubmit"
			textType="确定"
			ref="modifyRef"
		></disHistory>
	</view>
</template>

<script>
	import disHistory from '../../common/disHistory.vue'
	import {diseaseOrderSave,diseaseOrderGetDetails, getLastFillingRecord} from "@/api/engineeringMaintenance/engineeringMaintenance.js"
	import mixins from '@/utils/mixins.js'
	import {BS, BSM} from '@/session/index.js'
	import {getImageBase64} from "@/utils/imageOperation.js"
	import { doGet, doSave, doDelete } from "@/utils/offline/sqlite/index.js";
	//巡检的所有接口
	import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
	import { urlTobase64, uploadImageFromBase64} from '@/utils/imageOperation.js'
	import { uploadFile } from '@/utils/request'
	export default{
		name:'newDiseases',
		components: {
			disHistory
		},
		mixins:[mixins],
		data(){
			return {
				detailObj:{},
				beforeForm:{},
				imgs:[],
				requestStatus: false,
				isRequest:false
			}
		},
		methods: {
			async updateSubmit(obj) {
				this.$set(obj, 'projectId', uni.getStorageSync('isOwner'))
				const {result} =  await doGet(getLastFillingRecord, JSON.parse(uni.getStorageSync('lineData')))
				this.$set(obj,'inspectUser',result.inspectUser)
				// console.log('并更tab入参',obj )
				// return
				if(obj && obj.videoFileList && obj.videoFileList.length > 0){
					const taskArr = obj.videoFileList.filter(it => it.uploadStatus)
					if(taskArr.length > 0) {
						uni.showToast({
							title:'视频上传中,请稍等',
							icon:'none',
							mask:true
						})
						return
					}
				}
				if(this.requestStatus) return
				this.requestStatus = true
				// 删除视频记录的视频id
				let arr = [...obj.removeFileSet] || []
				if(arr.length) {
					await doc_deleteAttachs(arr)
				}
				doSave(XUNJIAN.diseaseOrderSave,{...obj})
				.then(res => {
					this.isRequest = true
					console.log(res, '变更tab确定按钮');     
					// uni.navigateBack()
					if(res.success) {
						uni.showToast({
							title:'成功!',
							icon:'none',
							mask:true,
						})
						setTimeout(() => {
							uni.navigateBack()
							this.requestStatus = false
						},1600)
					}else {
						this.requestStatus = false
					}
				})
			},   
			
		},
		async onLoad(params) {
			if(params && params.id) {
				this.mileage = params.type
				let imgs
				let obj_imgs
				let videos
				// diseaseOrderGetDetails({id:params.id})    
				
				doGet(XUNJIAN.diseaseOrderGetDetails, {id:params.id})
				.then(async res => {
					console.log(res,'变更详情');
					if(res.success) {	
						this.detailObj = res.result
						this.$set(this.detailObj,'diseaseGrade',res.result.diseaseGradeName)
						if (res.result.docId) {
							const attachRes = await doGet(getPicture, {docId:res.result.docId})
							// console.log(attachRes, '---81行变更tab页----');
							if(attachRes.success && attachRes.result) {
								let imgResult = attachRes.result.map(it => ({
									id:it.id,
									url: it.fileName
										?  this.$config.IMG_FILE_URL + it.fileName
										:  it.url 
								}))
							
								this.$set(this.detailObj, 'fileListImg', imgResult)
								this.detailObj.sourceImgs = JSON.parse(JSON.stringify(imgResult))
							}
						}
						//回显视频
						if (res.result.videoDocId) {
							const attachRes = await doGet(getPicture, {
								docId: res.result.videoDocId
							})
							if (attachRes.success && attachRes.result) {
								let videoResult = attachRes.result.map(it => ({
									id: it.id,
									url: it.fileName ?
										this.$config.VIDEO_URL + it.fileName :
										it.url
								}))
								this.$set(this.detailObj, 'videoFileList', videoResult)
								this.detailObj.sourceVideos = JSON.parse(JSON.stringify(videoResult))
							}
						}
						
						if(res.result.diseaseOrderLogDto && res.result.diseaseOrderLogDto.docId) {
							const attachRes = await doGet(getPicture, {docId:res.result.diseaseOrderLogDto.docId})
							console.log(attachRes, '---81行dto变更页----');
							if(attachRes.success && attachRes.result) {
								obj_imgs = attachRes.result.map(it => ({
									id:it.id,
									url: it.fileName
										?  this.$config.IMG_FILE_URL + it.fileName
										:  it.url 
								}))
							}
						}
						if (res.result.diseaseOrderLogDto && res.result.diseaseOrderLogDto.videoDocId) {
							const attachRes = await doGet(getPicture, {
								docId: res.result.diseaseOrderLogDto.videoDocId
							})
							if (attachRes.success && attachRes.result) {
								videos = attachRes.result.map(it => ({
									id: it.id,
									url: it.fileName ?
										this.$config.VIDEO_URL + it.fileName :
										it.url
								}))
								
							}
						}
						
						this.$set(this.detailObj, 'isInfluenceEquipment', false)
						this.$set(this.detailObj, 'isProtectionSection', false)
						this.$set(this.detailObj, 'isSandySoil', false)
						console.log(obj_imgs,'00000');
						if(res.result.diseaseOrderLogDto){
							let  diseaseOrderLogDto = res.result.diseaseOrderLogDto	
							//变更病害前对象(用同样的绑定值修改上面会影响到下面(例如备注等字段))
							this.beforeForm = {
								startMileage:this.getContent2(diseaseOrderLogDto),
								remark:diseaseOrderLogDto.diseaseRemarks || '',
								ringNumber:`${diseaseOrderLogDto.startNumber || ''}${diseaseOrderLogDto.startNumber && diseaseOrderLogDto.endNumber ? '-' : ''}${diseaseOrderLogDto.endNumber || ''}`,
								otherPosition:diseaseOrderLogDto.others || '',
								clockPosition:diseaseOrderLogDto.clockwisePosition || '',
								nowStatus:diseaseOrderLogDto.diseaseStatus || '',
								level:diseaseOrderLogDto.diseaseGradeName + (diseaseOrderLogDto.diseaseNo ? diseaseOrderLogDto.diseaseNo : ''),
								imgs:obj_imgs || [],
								videos:videos || [],
								inspectUser:diseaseOrderLogDto.inspectUser || '',
								measure:diseaseOrderLogDto.repairMethod || '',
								stationLocation:this.detailObj.stationLocation || '',
								createDate:diseaseOrderLogDto.createDate || '',
								createUserName:diseaseOrderLogDto.createUserName || ''
							}
							console.log(this.beforeForm,'变更前');
							//2.16-------------这里这样写是因为需要兼容组件disHostory回显
							this.$set(this.detailObj, 'isInfluenceEquipment', !!diseaseOrderLogDto.isInfluenceEquipment)
							this.$set(this.detailObj, 'isProtectionSection', !!diseaseOrderLogDto.isProtectionSection)
							this.$set(this.detailObj, 'isSandySoil', !!diseaseOrderLogDto.isSandySoil)
							// this.$set(this.detailObj, 'createDate', diseaseOrderLogDto.createDate)
							// this.$set(this.detailObj, 'createUserName', diseaseOrderLogDto.createUserName)
							this.$set(diseaseOrderLogDto, 'mileage', this.mileage)
						}

						const {lineId, lineSiteSectionId, lineSiteSectionType, pmId} = res.result
						let newest = await doGet(XUNJIAN.getLastFillingRecord,{lineId,lineSiteSectionId, lineSiteSectionType,pmId})
						console.log(newest, '上次填报记录的接口===');
						this.$set(this.detailObj, 'inspectUser', newest.result.inspectUser || '')
						this.$set(this.detailObj, 'updateIds', [])
						this.$set(this.detailObj, 'updateVideoIds', [])
						this.detailObj.removeFileSet = new Set()
						this.$refs.modifyRef.historyForm = this.detailObj
					}
				})
				
			}
		},
		async beforeDestroy() {
			if(!this.isRequest) {
				console.error('销毁钩子函数22',this.detailObj)
				// 新加图片后没有点击操作按钮直接退出 需要删除新加的id
				let needDelIds = [], needDelIds2 = []
				if(this.detailObj.updateIds.length) {
					let ids = this.detailObj.sourceImgs.map(i => i.id)
					needDelIds = this.getDifference(ids, this.detailObj.updateIds)
				}
				// 删除视频
				if(this.detailObj.updateVideoIds.length) {
					let ids = this.detailObj.sourceVideos.map(i => i.id)
					needDelIds2 = this.getDifference(ids, this.detailObj.updateVideoIds)
				}
				let allIds = [].concat(needDelIds, needDelIds2)
				if(allIds.length) {
					await doc_deleteAttachs(allIds)
				}
				// 找出删除的数据 原数据和现在的数组对比,并上传
				let result = this.getArrDifSameValue(this.detailObj.fileListImg, this.detailObj.sourceImgs || [])
				console.error(result)
				if(result.length) {
					let base64List = []
					let dataList = []
					for(let it of result) {
						const base64_img = await urlTobase64(it.url)
						base64List.push(base64_img.split(",")[1])
					}
					// 水印数据
					let formData = {}
					//区间/站点
					formData.name = this.detailObj.lineSiteSectionName
					//里程
					const distance = this.getContent2(this.detailObj)
					//环号
					const startRing = this.detailObj.startNumber || ''
					const endRing = this.detailObj.endNumber || ''
					const others = this.detailObj.others || ''
					const timeClock = this.detailObj.clockwisePosition || ''
					formData.ring =
						`${distance}${distance && startRing ? ',' : ''}${startRing}${startRing && endRing ? '~' : '' }${endRing}${(distance && others)||(endRing && others) ? ',' : ''}${others}${(distance && timeClock)  ||  (startRing && endRing && timeClock) || (others&&timeClock)  ? ',' : ''}${timeClock}`
					//现状
					formData.status = this.detailObj.diseaseStatus || ''
					formData.dateTime = this.getDate2(new Date)
					let response = await uploadImageFromBase64({
						dataList:[formData.name, formData.ring, formData.status, formData.dateTime],
						docId:this.detailObj.docId,
						base64List
					})
					console.error(response, '结果')
				}
				
				//找出删除的视频并且重新上传
				// let result2 = this.getArrDifSameValue(this.detailObj.videoFileList, this.detailObj.sourceVideos || [])
				// console.log(result2, '视频文件')
				// if(result2.length) {
				// 	for(let item of result2) {
				// 		uni.downloadFile({
				// 			url: item.url,
				// 			success: async (res) => {
				// 				if (res.statusCode === 200) {
				// 					console.error(res,'下载成功');
				// 					// #ifdef MP-WEIXIN
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.detailObj.videoDocId, },
				// 						name: 'attach',
				// 						filePath: res.tempFilePath,
				// 						isOffline: true
				// 					}
				// 					// #endif
									
				// 					// #ifdef APP-PLUS || H5
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.detailObj.videoDocId, },
				// 						files: [{
				// 							name: "attach",
				// 							uri: res.tempFilePath
				// 						}],
				// 						isOffline: true
				// 					}
				// 					// #endif
				// 					let data = await doSave(uploadFile, uploadResq)
				// 					console.error(data, '165行上传视频')
				// 				}
				// 			}
				// 		});
				// 	}
				// }
			}
			
		},
	}
</script>

<style lang="scss" scoped>

</style>